package com.sh.filesystem.service;

import com.sh.filesystem.entity.ShoaFile;
import com.sh.filesystem.mapper.IFileMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: he changjie on 2019/2/17
 * @Description:
 */
@Service
public class FileService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private IFileMapper fileMapper;

    /**
     * 添加一个文件
     * @param file 文件
     * @return
     */
    public int add(ShoaFile file){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = dateFormat.format(new Date());
        file.setUploadTime(time);
        return fileMapper.insertSelective(file);
    }

    /**
     *  删除一个文件
     * @param id 文件ID
     * @return
     */
    public int delete(String id){

        return fileMapper.deleteByPrimaryKey(id);
    }

    /**
     * 更新一个文件
     * @param file 文件
     * @return
     */
    public int update(ShoaFile file){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = dateFormat.format(new Date());
        file.setUploadTime(time);
        return fileMapper.updateByPrimaryKeySelective(file);
    }

    /**
     *  拉取一个文件
     * @param id 文件ID
     * @return
     */
    public ShoaFile queryOne(String id){
        return  fileMapper.selectByPrimaryKey(id);
    }

    /**
     * 分页
     * 查询所有文件
     * @param search 文件名
     * @param currentPage 当前页
     * @param pageSize 页尺寸
     * @return
     */
    public List<ShoaFile> queryAll(String search, int currentPage, int pageSize){
        RowBounds rowBunds = new RowBounds((currentPage - 1) * pageSize, pageSize);
        Example example = new Example(ShoaFile.class);
        example.setOrderByClause("upload_time desc,icon_type desc");
        Example.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotEmpty(search)){
            criteria.andLike("fileSourceName","%"+search+"%");
        }
        return fileMapper.selectByExampleAndRowBounds(example,rowBunds);
    }

    /**
     * 查询所有文件的数量
     * @param search 文件名
     * @return
     */
    public int queryAll(String search){
        Example example = new Example(ShoaFile.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotEmpty(search)){
            criteria.andLike("fileSourceName","%"+search+"%");
        }
        return fileMapper.selectCountByExample(example);
    }
}
